#!/bin/bash

# 性能测试脚本 - 测试限流功能
# 使用方法: ./test-performance.sh [BASE_URL] [CONCURRENT_REQUESTS] [TOTAL_REQUESTS]

BASE_URL="${1:-http://10.106.173.152:8080}"
CONCURRENT="${2:-10}"
TOTAL="${3:-100}"

echo "🚀 开始性能测试"
echo "📍 目标URL: $BASE_URL"
echo "🔄 并发数: $CONCURRENT"
echo "📊 总请求数: $TOTAL"
echo "----------------------------------------"

# 测试 /hello 端点
echo "📝 测试 /hello 端点..."
ab -n $TOTAL -c $CONCURRENT "$BASE_URL/hello" > results_hello.txt 2>&1

if [ $? -eq 0 ]; then
    echo "✅ /hello 测试完成"
    echo "📈 成功请求数: $(grep 'Complete requests' results_hello.txt | awk '{print $3}')"
    echo "❌ 失败请求数: $(grep 'Failed requests' results_hello.txt | awk '{print $3}')"
    echo "⏱️  平均响应时间: $(grep 'Time per request' results_hello.txt | head -1 | awk '{print $4}') ms"
else
    echo "❌ /hello 测试失败"
fi

echo "----------------------------------------"

# 测试 /diagnostic 端点
echo "📝 测试 /diagnostic 端点..."
ab -n $TOTAL -c $CONCURRENT "$BASE_URL/diagnostic" > results_diagnostic.txt 2>&1

if [ $? -eq 0 ]; then
    echo "✅ /diagnostic 测试完成"
    echo "📈 成功请求数: $(grep 'Complete requests' results_diagnostic.txt | awk '{print $3}')"
    echo "❌ 失败请求数: $(grep 'Failed requests' results_diagnostic.txt | awk '{print $3}')"
    echo "⏱️  平均响应时间: $(grep 'Time per request' results_diagnostic.txt | head -1 | awk '{print $4}') ms"
else
    echo "❌ /diagnostic 测试失败"
fi

echo "----------------------------------------"

# 测试 /test/rate-limit 端点（这个会触发限流）
echo "📝 测试 /test/rate-limit 端点（限流测试）..."
ab -n $TOTAL -c $CONCURRENT "$BASE_URL/test/rate-limit" > results_ratelimit.txt 2>&1

if [ $? -eq 0 ]; then
    echo "✅ /test/rate-limit 测试完成"
    echo "📈 成功请求数: $(grep 'Complete requests' results_ratelimit.txt | awk '{print $3}')"
    echo "❌ 失败请求数: $(grep 'Failed requests' results_ratelimit.txt | awk '{print $3}')"
    echo "⏱️  平均响应时间: $(grep 'Time per request' results_ratelimit.txt | head -1 | awk '{print $4}') ms"
    echo "🔒 HTTP 429 状态码数量: $(grep '429' results_ratelimit.txt | wc -l)"
else
    echo "❌ /test/rate-limit 测试失败"
fi

echo "----------------------------------------"

# 使用 curl 进行快速连续请求测试
echo "📝 快速连续请求测试（限流验证）..."
SUCCESS_COUNT=0
RATE_LIMITED_COUNT=0

for i in {1..20}; do
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "$BASE_URL/test/rate-limit")
    if [ "$HTTP_CODE" = "200" ]; then
        SUCCESS_COUNT=$((SUCCESS_COUNT + 1))
    elif [ "$HTTP_CODE" = "429" ]; then
        RATE_LIMITED_COUNT=$((RATE_LIMITED_COUNT + 1))
    fi
    echo -n "."
done

echo ""
echo "✅ 成功响应: $SUCCESS_COUNT"
echo "🔒 限流响应 (429): $RATE_LIMITED_COUNT"

echo "----------------------------------------"
echo "📄 详细结果已保存到:"
echo "   - results_hello.txt"
echo "   - results_diagnostic.txt" 
echo "   - results_ratelimit.txt"
echo ""
echo "💡 分析建议:"
echo "   - 如果看到 429 状态码，说明限流功能正常工作"
echo "   - /hello 和 /diagnostic 不应该被限流"
echo "   - /test/rate-limit 可能会被限流（取决于配置）"
echo ""
echo "🎉 性能测试完成！" 